package com.smart.framework.helper;

import java.lang.reflect.Field;
import java.util.Map;

import com.smart.framework.annotation.Inject;
import com.smart.framework.util.ArrayUtil;
import com.smart.framework.util.ConllectionUtil;
import com.smart.framework.util.ReflectionUtil;

/**
 * 依赖注入帮助类
 * 
 * @author CrazyShaQiuShi
 *
 */
public final class IocHelper {

	static {
		// 获取所有的bean类与Bean之间的映射关系
		Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
		if (ConllectionUtil.isEmpty(beanMap)) {
			// 便利map
			for (Map.Entry<Class<?>, Object> beanEntity : beanMap.entrySet()) {
				// 从BeanMap中获取Bean类与Bean实例
				Class<?> beanClass = beanEntity.getKey();
				Object beanInstance = beanEntity.getValue();
				// 获取Bean中所有成员变变量
				Field[] beanFields = beanClass.getDeclaredFields();
				if (ArrayUtil.isNotEmpty(beanFields)) {
					// 便利bean Field
					for (Field beanField : beanFields) {
						// 判断当前Bean是否带有Inject注解
						if (beanField.isAnnotationPresent(Inject.class)) {
							// 在bean Map中获取Bean Field的实例
							Class<?> beanFieldClass = beanField.getType();
							Object beanFieldInstance = beanMap.get(beanFieldClass);
							if (beanFieldInstance != null) {
								// 通过反射初始化BeanField的值
								ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
							}

						}
					}
				}
			}
		}
	}
}
